import { Component } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

function userNameValidator(control: FormControl): { [s: string]: boolean } {
  if (!control.value.match(/^zime/)) {
    return { invalidUser: true }
  }
  else {
    return {};
  }
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  myForm!: FormGroup;//对应登录表单
  userName!: AbstractControl;//对应用户名的输入
  password!: AbstractControl;//对应密码的输入
  //创建表单----------------↓
  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group(
      {
        'userName': ['', Validators.compose([Validators.required, userNameValidator, Validators.minLength(7)])],//要求必须填写
        'password': ['', Validators.compose([Validators.required, Validators.minLength(6)])]//要求必须填写，且最小长度为6，compose为组合
      }
    );
    this.userName = this.myForm.controls['userName'];
    this.password = this.myForm.controls['password'];
  }
  //------------------------↑
  onSubmit(value: any) {
    console.log(value);
  }
}
